package org.example.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    public static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    public static final String accessKeyId = "LTAI5tPz5icgQuksk187YkFJ";
    public static final String accessKeySecret = "oELlAmlYRIYJduhDP8lnFobq7DohMq";
    public static final String bucketName = "animal-s";
    public static final String imageUrl = "https://animal-s.oss-cn-beijing.aliyuncs.com";


    /**
     * 文件上传
     *
     * @param filename
     * @param in
     * @return
     */
    public static String upload(String filename, InputStream in) {
        //3、拼写图片路径
        filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 填写Byte数组。
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, filename, in);

        // 关闭OSSClient。
        ossClient.shutdown();

        String url = imageUrl + "/" + filename;
        return url;
    }
}
